package net.openadventure;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;

import javax.swing.JComponent;
import javax.swing.JPanel;

public class BackgroundCanvas {

    private BufferedImage background = null; // The background image of the screen
    
    private JPanel panel;

    /**
     * Creates a panel to draw the background image on the screen
     * 
     * @param width The preferred width of the canvas
     * @param height The preferred height of the canvas
     */
    public BackgroundCanvas(int width, int height) {
        panel = new BCJPanel(true);
        
        panel.setPreferredSize(new Dimension(width, height));
    }

    /**
     * Sets the background image to the image specified.
     * 
     * @param img
     *            The new image
     */
    public void setImage(BufferedImage img) {
        background = img;
    }

    /**
     * Sets the preferred size of the canvas
     * @param width The preferred width of the canvas
     * @param height The preferred height of the canvas
     */
    public void setDimension(int width, int height) {
        panel.setPreferredSize(new Dimension(width, height));
    }
    
    public JComponent getJPanel() {
        return panel;
    }

    private class BCJPanel extends JPanel {

		private static final long serialVersionUID = 299740814708347727L;

		public BCJPanel(boolean arg0) {
            super(arg0);
        }

        /**
         * The overridden method to control painting of the background on the screen
         */
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            // Convert Graphics to Graphics2D for added functionality.
            Graphics2D g2 = (Graphics2D) g;

            // Draw the current background image first
            g2.drawImage(background, 0, 0, this.getWidth(), this.getHeight(), this);
        }
    }
}
